<?php

namespace Common\Logic;

use Common\Util\Easemob;
use Common\Logic\MessageLogic;

/**
 * IM
 */
class ImLogic
{

      public $Easemob;

      public $FriendModel;

      public $GroupModel;

      public function __construct()
      {
            $this->Easemob = new Easemob;
            $this->FriendModel = M("user_friend");
            $this->GroupModel = M("im_group");
      }

      /**
       * 获取远程的用户好友
       * @param user_id 
       * @param offset 分页获取(第几页) 默认全部
       * @param update 是否强制更新
       * @param simpleData 是否获取最简单的数据[uid1,uid2]
       */ 
      public function getFriendListRemote($user_id = 0, $offset = 0,$update = false,$simpleData = false)
      {
            #看缓存，如果缓存有就直接给了，如果没有就算了
            $cache = S("USER_REMOTE_FLIST_".$user_id);
            if( $cache && !$update )
            {
                  $list = $cache;
            }else{
                  $list = $this->Easemob->showFriends($user_id);
                  #缓存120s
                  S("USER_REMOTE_FLIST_".$user_id,$list,120);
                  #理论上要写入到本地系统中
            }

            if( $simpleData )
            {
                  return $list;
            }

            $res = [
                  "count" => count($list),
                  "list" => []
            ];

            $select_list = $list;

            #如果是分页获取
            if( $offset > 0 )
            {
                  $select_list = array_slice( $select_list, ($offset - 1)*10, 10 );
            }
            
            $list = [];
            foreach($select_list as $v)
            {
                  $user = $this->getUserInfoById($v);
                  if($user)
                  {
                        $list[] = $user;
                  }
            }
            unset($v);
            $res['list'] = $list;

            return $res;
      }

	#获取好友列表(本地)
      public function getFriendList($user_id = 0, $offset = 10)
      {

            $query = "( user_id={$user_id} OR friend_id={$user_id} ) AND status=1";
            $result = [];
            $result['count'] = $this->FriendModel->where($query)->fetchSql(0)->count();// 查询满足要求的总记录数
            $Page = new \Think\Page($result['count'], $offset);// 实例化分页类 传入总记录数和每页显示的记录数
            $result['list'] = $this->FriendModel->where($query)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->fetchSql(0)->select();

            foreach ($result['list'] as $k => &$v) {
                  if ($v['user_id'] == $user_id) {
                        $v = $this->getUserInfoById($v['friend_id']);
                  } else {
                        $v = $this->getUserInfoById($v['user_id']);
                  }
            }

            return $result;
      }

	#申请加某人为好友

      public function addFriend($user_id, $friend_id)
      {

            $me = $this->getUserInfoById($user_id);
            if ($user_id == $friend_id || !$me)
                  return ['status' => 0, 'msg' => '参数错误', 'result' => ''];
            $friend = $this->getUserInfoById($friend_id);

            if (!$friend)
                  return ['status' => 0, 'msg' => '用户不存在', 'result' => ''];

            $isFriend = $this->isFriend($user_id, $friend_id);

            if ($isFriend) {
                  if ($isFriend['status'] == 1)
                        return ['status' => 0, 'msg' => '已经是好友了', 'result' => ''];

         #如果原来是对方提交过的，直接同意
                  if ($isFriend['user_id'] == $friend_id) {
                        return $this->confirmFirend($isFriend['id'], true);
                  }

                  if ($isFriend['status'] == 0)
                        return ['status' => 0, 'msg' => '已经提交过好友申请了', 'result' => ''];

                  $action = $this->FriendModel->where(["id" => $isFriend['id']])->save([
                        "status" => 0
                  ]);

                  if (false === $action)
                        return ['status' => 0, 'msg' => '提交失败', 'result' => ''];

            } else {
                  $action = $this->FriendModel->add([
                        "user_id" => $user_id,
                        "friend_id" => $friend_id,
                        "remark_name_a" => "",
                        "remark_name_b" => "",
                        "create_time" => time(),
                        "update_time" => 0,
                  ]);
                  if (!$action)
                        return ['status' => 0, 'msg' => '提交失败', 'result' => ''];
            }
		
            #发送系统消息

            MessageLogic::sendUserMsg([
                  "user_id" => $friend_id,
                  "title" => "添加好友请求",
                  "content" => $me['nickname'] . "请求添加你为好友",
                  "type" => MessageLogic::FRIEND_MSG,
                  "notice" => true,
                  "ext" => [
                        "friend_id" => $user_id,
                        "id" => $isFriend ? $isFriend['id'] : $action
                  ]
            ]);

            return ['status' => 1, 'msg' => '提交成功，等待对方同意', 'result' => ''];
      }

      #同意加好友
      /**
       * @param $id (好友表id，如果不传，下面的参数必须传)
       * @param $user_id 
       * @param $friend_id 
       * @param $$force 强制通过
       */
      public function confirmFirend($data = [], $force = false)
      {
            if (isset($data['id'])) {
                  $isFriend = $this->FriendModel->where(["id" => $data['id']])->find();
            } elseif (isset($data['user_id']) && isset($data['friend_id'])) {
                  $isFriend = $this->isFriend($data['user_id'], $data['friend_id']);
            } else {
                  return ['status' => 0, 'msg' => '参数错误', 'result' => ''];
            }

            if (!$isFriend)
                  return ['status' => 0, 'msg' => '无法找到好友申请记录', 'result' => ''];

            if ($isFriend['status'] == 1)
                  return ['status' => 0, 'msg' => '已经是好友了', 'result' => ''];

            if (!$force && $isFriend['status'] == 2)
                  return ['status' => 0, 'msg' => '已经拒绝好友请求', 'result' => ''];

            $action = $this->FriendModel->where(["id" => $isFriend['id']])->save([
                  "status" => 1
            ]);


            if (false === $action)
                  return ['status' => 0, 'msg' => '处理失败', 'result' => ''];

            $im = $this->Easemob->addFriend($isFriend['user_id'], $isFriend['friend_id']);

            #发送系统消息
            $me = $this->getUserInfoById($isFriend['friend_id']);

            MessageLogic::sendUserMsg([
                  "user_id" => $isFriend['user_id'],
                  "title" => "同意了好友请求",
                  "content" => $me['nickname'] . "和你已经成为了好友",
                  "type" => MessageLogic::FRIEND_MSG,
                  "notice" => true,
                  "ext" => [
                        "friend_id" => $isFriend['friend_id'],
                        "id" => $isFriend['id']
                  ]
            ]);

            return ['status' => 1, 'msg' => '处理成功', 'result' => ''];
      }

      #拒绝加好友
      /**
       * @param $id (好友表id，如果不传，下面的参数必须传)
       * @param $user_id 
       * @param $friend_id 
       * @param $$force 强制拒绝
       */
      public function refuseFirend($data = [], $force = false)
      {
            if (isset($data['id'])) {
                  $isFriend = $this->FriendModel->where(["id" => $data['id']])->find();
            } elseif (isset($data['user_id']) && isset($data['friend_id'])) {
                  $isFriend = $this->isFriend($data['user_id'], $data['friend_id']);
            } else {
                  return ['status' => 0, 'msg' => '参数错误', 'result' => ''];
            }

            if (!$isFriend)
                  return ['status' => 0, 'msg' => '无法找到好友申请记录', 'result' => ''];

            if ($isFriend['status'] == 1)
                  return ['status' => 0, 'msg' => '已经是好友了', 'result' => ''];

            if ($isFriend['status'] == 2)
                  return ['status' => 0, 'msg' => '已经拒绝好友请求', 'result' => ''];

            $action = $this->FriendModel->where(["id" => $isFriend['id']])->save([
                  "status" => 2
            ]);

            if (false === $action)
                  return ['status' => 0, 'msg' => '处理失败', 'result' => ''];

            #发送系统消息

            $me = $this->getUserInfoById($isFriend['friend_id']);

            MessageLogic::sendUserMsg([
                  "user_id" => $isFriend['user_id'],
                  "title" => "拒绝了好友请求",
                  "content" => $me['nickname'] . "拒绝和你成为好友",
                  "type" => MessageLogic::FRIEND_MSG,
                  "notice" => true,
                  "ext" => [
                        "friend_id" => $isFriend['friend_id'],
                        "id" => $isFriend['id']
                  ]
            ]);

            return ['status' => 1, 'msg' => '处理成功', 'result' => ''];
      }

      #删除好友
      public function delFriend($user_id, $friend_id)
      {
            if ($user_id == $friend_id)
                  return ['status' => 0, 'msg' => '参数错误', 'result' => ''];

            $friend = $this->getUserInfoById($friend_id);

            if (!$friend)
                  return ['status' => 0, 'msg' => '用户不存在', 'result' => ''];

            $isFriend = $this->isFriend($user_id, $friend_id);

            if ($isFriend) {
                  if (0 == $isFriend['status'] || 2 == $isFriend['status'])
                        return ['status' => 0, 'msg' => '两人并非好友', 'result' => ''];

                  $action = $this->FriendModel->where(["id" => $isFriend['id']])->delete();

                  if (!$action)
                        return ['status' => 0, 'msg' => '删除好友失败', 'result' => ''];

                  $im = $this->Easemob->deleteFriend($user_id, $friend_id);

                  return ['status' => 1, 'msg' => '删除好友成功', 'result' => ''];
            } else {
                  return ['status' => 0, 'msg' => '两人并非好友', 'result' => ''];
            }

      }

      /**
       * 判断是否好友（根据远程的结果判断）
       * 判断$user_id是否 好友$friend_id
       */
      public function isFriend($user_id, $friend_id, $check = false)
      {
            
            $friends = $this->getFriendListRemote($user_id,0,false,true);
            
            if( !in_array($friend_id,$friends) )
            {
                  return false;
            } 

            if ($check) return true;

            #构造和好友模型一致的数据
            return [
                  "user_id" => $user_id,
                  "friend_id" => $friend_id,
                  "remark_name_a" => "",
                  "remark_name_b" => "",
                  "status" => 1,
                  "create_time" => time(),
                  "update_time" => time(),
            ];
      }

      /**
       * 判断本地是否好友
       * 判断$user_id是否 好友$friend_id
       */
      public function isFriendLocal($user_id, $friend_id, $check = false)
      {
            $record = $this->FriendModel->where([
                  "user_id" => $user_id,
                  "friend_id" => $friend_id
            ])->find();

            if (!$record) {
                  $record = $this->FriendModel->where([
                        "user_id" => $friend_id,
                        "friend_id" => $user_id
                  ])->find();
            }

            if (!$check)
                  return $record;

            if ($record)
                  return $record['status'] == 1 ? true : false;

            return false;
      }

      #创建群
      /**
       * @param user_id  创建人id
       * @param name 群名称
       * @param avatar 群头像
       * @param desc 群公告
       * @param firend_ids 数组json字符串 可空 
       **/
      public function createGroup($data = [])
      {
            if (!array_key_exists("user_id", $data))
                  return ['status' => 0, 'msg' => '群主不存在', 'result' => ''];

            $createGroupParams = [
                  "owner" => (string)$data['user_id'],
                  "allowinvites" => true,
                  "maxusers" => 2000,
                  "public" => false,
                  "members_only" => false,
                  "allowinvites" => true,
                  "approval" => true,
                  "approval" => true,
                  "groupname" => $data['name'],
                  "desc" => isset($data['desc']) ? $data['desc'] : ""
            ];
 
            #检查群成员中是否有用户不是他的好友
            if (array_key_exists("friend_ids", $data)) {
                  $friend_ids = is_array($data['friend_ids']) ? $data['friend_ids'] : json_decode($data['friend_ids'], true);

                  $should_name = false;

                  if (!array_key_exists("name", $data)) {
                        $should_name = true;
                        $me = $this->getUserInfoById($data['user_id']);
                        $data['name'] = $me && !empty($me['nickname']) ? [$me['nickname']] : [];
                  }

                  #去重，检查好友
                  $ids = [];
                  foreach ($friend_ids as $value) {
                        // if ($value != $data['user_id'] && $this->isFriend($data['user_id'], $value, true)) {
                        if ($value != $data['user_id']) {
                              $ids[] = $value;
                              if ($should_name) {
                                    $user = $this->getUserInfoById($value);
                                    if ($user && !empty($user['nickname'])) {
                                          $data['name'][] = $user['nickname'];
                                    }
                              }
                        }
                  }
                  // var_dump($ids);exit();
                  
                  unset($value);
                  if (!empty($ids)) {
                        $createGroupParams['members'] = $ids;
                  } 
                  // else {
                  //       return ['status' => 0, 'msg' => '群创建失败，你和所邀请的人并非好友', 'result' => $ids];
                  // }


                  if (!empty($data['name'])) {
                        if (is_array($data['name']))
                              $data['name'] = substr(implode("、", $data['name']), 0, 16);
                  } else {
                        unset($data['name']);
                  }
            }

            if (!array_key_exists("name", $data))
                  return ['status' => 0, 'msg' => '群名称无效', 'result' => $createGroupParams];

            if (!array_key_exists("avatar", $data))
                  return ['status' => 0, 'msg' => '群头像无效', 'result' => $createGroupParams];

            if ($this->GroupModel->where(["name" => $data['name']])->find())
                  return ['status' => 0, 'msg' => '该群名称已存在', 'result' => $createGroupParams];

            $im = $this->Easemob->createGroup($createGroupParams);

            if (!$im)
                  return ['status' => 0, 'msg' => '群创建失败', 'result' => 'im创建失败'];

            $db = $this->GroupModel->add([
                  "owner" => $data['user_id'],
                  "groupid" => $im['data']['groupid'],
                  "name" => $data['name'],
                  "avatar" => $data['avatar'],
                  "desc" => isset($data['desc']) ? $data['desc'] : "",
                  "create_time" => time(),
                  "update_time" => 0
            ]);

            if (!$db) {
                  $this->Easemob->deleteGroup($im['data']['groupid']);
                  return ['status' => 0, 'msg' => '群创建失败', 'result' => ''];
            }

            return ['status' => 1, 'msg' => '创建成功', 'result' => $this->GroupModel->where(['id' => $db])->find()];
      }

      #修改群
      /**
       * @param id/groupid  id/im系统群id
       * @param name 群名称
       * @param avatar 群头像
       * @param desc 群公告
       **/
      public function modifyGroup($data = [])
      {
            $where = [];

            if (array_key_exists("id", $data))
                  $where['id'] = $data['id'];

            if (array_key_exists("groupid", $data))
                  $where['groupid'] = $data['groupid'];

            if (empty($where))
                  return ['status' => 0, 'msg' => '参数错误', 'result' => ''];

            $group = $this->GroupModel->where($where)->find();

            if (!$group)
                  return ['status' => 0, 'msg' => '群不存在', 'result' => ''];

            $update = [];

            if (array_key_exists("name", $data)) {
                  $g = $this->GroupModel->where(["name" => $data['name']])->find();
                  if ($g && $g['id'] != $group['id'])
                        return ['status' => 0, 'msg' => '该群名称已存在', 'result' => ''];
                  $update['name'] = $group['name'] = $data['name'];
            }

            if (array_key_exists("avatar", $data))
                  $update['avatar'] = $group['avatar'] = $data['avatar'];

            if (array_key_exists("desc", $data))
                  $update['desc'] = $group['desc'] = $data['desc'];

            if (empty($update))
                  return ['status' => 0, 'msg' => '更新信息无效', 'result' => ''];

            $group['update_time'] = time();

            $db = $this->GroupModel->where(["id" => $group['id']])->save($update);

            if (false === $db)
                  return ['status' => 0, 'msg' => '更新信息失败', 'result' => ''];


            $im = $this->Easemob->modifyGroupInfo($group['groupid'], [
                  "groupname" => $group['name'],
                  "description" => $group['desc']
            ]);

            return ['status' => 1, 'msg' => '信息更新成功', 'result' => $group];
      }

      #拉人进群，必须是好友, 2018-10-08修改，支持非好友进群
      /**
       * @param user_id  拉人的用户id
       * @param groupid IM系统群id
       * @param friend_id 被拉入群的用户id  支持多人id array数组
       **/
      public function joinGroup($data = [])
      {
            if (!array_key_exists("user_id", $data))
                  return ['status' => 0, 'msg' => '邀请人参数错误', 'result' => ''];

            if (!array_key_exists("groupid", $data))
                  return ['status' => 0, 'msg' => '群参数错误', 'result' => ''];

            if (!array_key_exists("friend_id", $data) || empty($data['friend_id']))
                  return ['status' => 0, 'msg' => '被邀请人参数错误', 'result' => ''];

            $friend_ids = json_decode($data['friend_id'], true);

            $group = $this->GroupModel->where([
                  "groupid" => $data['groupid'],
                  "status" => 1
            ])->find();

            if (!$group)
                  return ['status' => 0, 'msg' => '群不存在', 'result' => ''];
            
            // if( $data['user_id'] != $group['owner'])
            //       return ['status' => 0, 'msg' => '只有群主可以邀请', 'result' => ''];

            if (is_array($friend_ids)) {
                  // $joins = [];

                  // foreach ($friend_ids as $k => $v) {
                  //       if (empty($v) || !is_numeric($v)) {
                  //             continue;
                  //       }

                  //       // if (!$this->isFriend($data['user_id'], $v, true)) {
                  //       //       continue;
                  //       // }

                  //       $joins[$k] = $v;
                  // }

                  if (empty($friend_ids)) {
                        // return ['status' => 0, 'msg' => '被邀请人全部非好友关系或者无效', 'result' => ''];
                        return ['status' => 0, 'msg' => '被邀请人无效', 'result' => ''];
                  }
                  // var_dump($joins); exit();

                  $im = $this->Easemob->addGroupMembers($group['groupid'], $friend_ids);

            } else {
                  // if (!$this->isFriend($data['user_id'], $data['friend_id'], true))
                  //       return ['status' => 0, 'msg' => '二人非好友关系，无法邀请加群', 'result' => ''];

                  $im = $this->Easemob->addGroupMember($group['groupid'], $data['friend_id']);

            }

            if (!$im)
                  return ['status' => 0, 'msg' => '邀请加群失败', 'result' => ''];

            return ['status' => 1, 'msg' => '邀请加群成功', 'result' => ''];
      }

      #退群
      /**
       * @param id/groupid  id/im系统群id
       * @param user_id id/array json 支持多人
       * @param Actionuser_id id操作人
       */
      public function quitGroup($data = [], $Actionuser_id = NULL)
      {
            if (isset($data['groupid'])) {
                  $group = $this->GroupModel->where(["groupid" => $data['groupid']])->find();
            } elseif (isset($data['id'])) {
                  $group = $this->GroupModel->where(["id" => $data['id']])->find();
            }

            if (!$group)
                  return ['status' => 0, 'msg' => '群不存在', 'result' => ''];

            if( $Actionuser_id && $Actionuser_id != $group['owner'] )
            {
                  return ['status' => 0, 'msg' => '只有群主能操作', 'result' => ''];
            }

            if( is_numeric($data['user_id']) )
            {
                  if( $data['user_id'] == $group['owner'] )
                  {
                        return ['status' => 0, 'msg' => '群主务必留下', 'result' => ''];
                  }
                  $im = $this->Easemob->deleteGroupMember($group['groupid'], $data['user_id']);
            }else{
                  $users = is_array($data['user_id']) ? $data['user_id'] : \json_decode($data['user_id'], true);
                  if( in_array($group['owner'], $users) )
                  {
                        return ['status' => 0, 'msg' => '群主务必留下', 'result' => ''];
                  }
                  $im = $this->Easemob->deleteGroupMembers($group['groupid'], $users);
            }

            return $im ? ['status' => 1, 'msg' => '操作成功', 'result' => ''] : ['status' => 0, 'msg' => '操作失败', 'result' => ''];
      }

      #获取群成员
      /**
       * @param id/groupid  id/im系统群id
       * @param page
       * @param page_size
       */
      public function getGroupMembers($data = [])
      {
            if (isset($data['groupid'])) {
                  $group = $this->GroupModel->where(["groupid" => $data['groupid']])->find();
            } elseif (isset($data['id'])) {
                  $group = $this->GroupModel->where(["id" => $data['id']])->find();
            }

            if (!$group)
                  return ['status' => 0, 'msg' => '群不存在', 'result' => ''];

            $res = $this->Easemob->getGroupUsers($group['groupid']);

            $members = ($res && isset($res['data']) && !empty($res['data'])) ? $res['data'] : [];

            $result = [];

            $owner = $this->getUserInfoById($group['owner']);
            if( $owner )
                  $result[] = $owner;

            foreach ($members as $k => $v) {
         // var_dump($v);
                  if (isset($v['member'])) {
                        $m = $this->getUserInfoById($v['member']);
                        if ($m)
                              $result[] = $m;
                  }
            }

            return ['status' => 1, 'msg' => 'ok', 'result' => $result];
      }

       #获取群成员（纯数组，包含群主）
      /**
       * @param id/groupid  id/im系统群id
       */
      public function getGroupMembersArray($data = [])
      {
            if (isset($data['groupid'])) {
                  $group = $this->GroupModel->where(["groupid" => $data['groupid']])->find();
            } elseif (isset($data['id'])) {
                  $group = $this->GroupModel->where(["id" => $data['id']])->find();
            }

            if (!$group)
                  return [];

            $res = $this->Easemob->getGroupUsers($group['groupid']);

            $members = [];

            if( $res && isset($res['data']) && !empty($res['data']) )
            {
                  $owner = array_column($res['data'], 'owner');
                  $owner = $owner?$owner[0] : 0;
                  $members = array_column($res['data'], 'member');
                  if( $owner )
                  array_unshift($members, $owner);
            }
            
            return $members;
      }

      /**
       * 获取用户的群
       * @param user_id
       * @param update 是否强制更新
       */
      public function getGroupsForUser($user_id,$update = false)
      {
            $cache = S("USER_IM_GROUP_".$user_id);
            if( $cache && !$update )
            {
                  $list = $cache;
            }else{
                  $list = $this->Easemob->getGroupsForUser($user_id);
                  S("USER_IM_GROUP_".$user_id,$list,120);
            }
            // var_dump($list);
            $result = [];

            if (!$list || !isset($list['data']) || empty($list['data']))
                  return ['status' => 1, 'msg' => 'ok', 'result' => $result];

            foreach ($list['data'] as $k => $v) 
            {
                  $gv = $this->getGroupInfoByGroupId($v['groupid']);
                  if( !$gv )
                  {
                        #本地没有这个群，写入吧
                        $gv = [
                              "groupid" => $v['groupid'],
                              "name" => $v['groupname'],
                              "owner" => 0,
                              "avatar" => "",
                              "desc" => "",
                              "maxusers" => 2000,
                              "owner_auth" => 0,
                              "status" => 1,
                              "create_time" => time(),
                              "update_time" => 0
                        ];

                        $gv['id'] = $this->GroupModel->add($gv);
                  }else{
                        $gv['name'] = $v['groupname'];
                        $gv['avatar'] = parseMediaUrl($gv['avatar']);
                  }
                  $result[] = $gv;
            }
            unset($k);
            unset($v);
            return ['status' => 1, 'msg' => 'ok', 'result' => $result];
      }

      /** 
       * 群主获取推荐的可以拉进群的用户信息
       * @param user_id
       * @param group_id
       * @param page
       * @return array
      */
      public function recoUsers( $user_id = NULL, $group_id = NULL,$page = 1)
      {
            $group = $this->GroupModel->where(["groupid" => $group_id])->find();

            if( !$group || $group['owner_auth'] == 0 )
            {
                  return [];
            }

            if( empty($user_id) || empty($group_id) )
            {
                $users = M('users')->where("user_id != $user_id")->order('pay_points desc')->field('user_id,head_pic,nickname,pay_points as flag')->page($page,20)->select();
                foreach($users as $k => &$v)
                {
                    $v['head_pic'] = parseMediaUrl($v['head_pic']);
                }
                return $users;
            }

            $members = [];
            $owner = 0;

            try{

                  $res = $this->Easemob->getGroupUsers($group_id);            

                  if( $res && isset($res['data']) && !empty($res['data']) )
                  {
                        $owner = array_column($res['data'], 'owner');
                        $owner = $owner?$owner[0] : 0;
                        $members = array_column($res['data'], 'member');
                        if( $owner )
                        array_unshift($members, $owner);
                  }
            }catch(\Exception $e)
            {

            }

            if( $user_id != $owner ) return [];

            $where = [];

            if( $members )
            {
                  // var_dump($members,$owner);
                  $where['user_id'] = ['not in',$members];
            }        

            $users = M('users')->where($where)->order('pay_points desc')->field('user_id,head_pic,nickname,pay_points as flag')->page($page,20)->select();

            foreach($users as $k => &$v)
            {
                  $v['head_pic'] = parseMediaUrl($v['head_pic']);
            }

            return $users;
      }
      
      /**
       * 获取单个群信息
       * @param group_id 
       * @return 
       */ 
      public function getGroupInfo($group_id)
      {
            $info = $this->Easemob->getGroupDetail([$group_id]);

            if( $info && $info[0] )
            {
                  $info  = $info[0];
                  $gp = $this->GroupModel->where([
                        "groupid" => $group_id
                  ])->find();
                  
                  $updateGroup = false;
                  if( $gp && ( $gp['name'] != $info['name'] || $gp['desc'] != $info['description'] ) )
                  {
                        $updateGroup = true;
                  }
                  
                  $gp["name"] = $info['name'];
                  $gp["desc"] = $info['description'];                  
                  if( $gp )
                  {
                        if( $updateGroup )
                        {
                              $this->GroupModel->where([
                                    "groupid" => $group_id
                              ])->save($gp);
                        }
                  }else{
                        $gp["owner_auth"] = 0;
                        $gp['groupid'] = $info['id'];
                        $gp['owner'] = $info['owner'];
                        $gp['maxusers'] = $info['maxusers'];
                        $gp['status'] = 1;
                        $gp['create_time'] = time();
                        $gp['id'] = $this->GroupModel->add($gp);
                  }

                  $gp['avatar'] = \parseMediaUrl( $gp['avatar'] );

                  $gp['members_count'] = isset($info['affiliations_count']) ? $info['affiliations_count'] : 1;
                  $gp['can_speak'] = isset($gp['can_speak']) ? $gp['can_speak'] : 1;

                  return $gp;
            }

            return $info;
      }

      // 全员禁言开关
      // $switch 0 禁言 1关闭禁言
      // return bool
      public function can_speak_switch($groupid, $switch = 0)
      {
            $update = $this->GroupModel->where([
                  'groupid' => $groupid,
            ])->save([
                  'can_speak' => $switch,
                  'update_time' => time()
            ]);

            if( $update !== false)
            {	
                  #发送透传消息
                  $action = $switch == 1 ? 'CAN_SPEAK' : 'CANT_SPEAK';
                  $ext = $switch == 1 ? [
                        'message' => '管理员关闭了全员禁言'
                  ]: [
                        'message' => '管理员开启了全员禁言'
                  ];
                  $sendMsg = $this->Easemob->sendCmd('admin', 'chatgroups', [$groupid], $action, $ext);
                  return true;
            }
            return false;
      }

      public function getUserInfoById($user_id)
      {
            $res = M("users")->where(["user_id" => $user_id])->cache(300)->field("user_id,sex,nickname,head_pic")->cache(300)->find();
            
            if( $res )
            {
                  $res['head_pic'] = parseMediaUrl($res['head_pic']);
            }

            return $res;
      }

      protected function getUserInfoByTel($tel)
      {
            $res = M("users")->where(["mobile" => $tel])->cache(300)->field("user_id,sex,nickname,head_pic,mobile")->find();
            
            if( $res )
            {
                  $res['head_pic'] = parseMediaUrl($res['head_pic']);
            }

            return $res;
      }

      protected function getGroupInfoById($id)
      {
            //->field("id,groupid,name,owner,name,desc,create_time")
            return $this->GroupModel->where(["id" => $id])->cache(30)->find();
      }

      protected function getGroupInfoByGroupId($groupid)
      {
            return $this->GroupModel->where(["groupid" => $groupid])->cache(30)->find();
      }
}